package edu.ptu.shortlink.admin.common.biz.user;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import edu.ptu.shortlink.admin.common.convention.exception.ClientException;
import edu.ptu.shortlink.admin.common.convention.result.Results;
import edu.ptu.shortlink.admin.config.UserFlowRiskControlConfiguration;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

import static edu.ptu.shortlink.admin.common.convention.errorcode.BaseErrorCode.FLOW_LIMIT_ERROR;

/**
 * @BelongsProject: short-link
 * @BelongsPackage: edu.ptu.shortlink.admin.common.biz.user
 * @Author: HYJ
 * @CreateTime: 2025-05-14  21:41
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
public class UserFlowRiskControlFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;
    private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;

    private static final String USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH = "lua/user_flow_risk_control.lua";


    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 初始化Redis脚本执行器
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();

        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH)));
        redisScript.setResultType(Long.class);

        // 获取用户名，未登录用户使用"other"作为标识
        String username = Optional.ofNullable(UserContext.getUsername()).orElse("other");
        // 执行Lua脚本，获取当前访问次数
        Long result = null;
        try {
            result = stringRedisTemplate.execute(redisScript, Lists.newArrayList(username), userFlowRiskControlConfiguration.getTimeWindow(), String.valueOf(userFlowRiskControlConfiguration.getMaxAccessCount()));
        } catch (Throwable e) {
            log.error("执行Redis脚本失败", e);
            returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
        }

        // 如果访问次数超过限制，返回错误信息
        if (result != null && result > userFlowRiskControlConfiguration.getMaxAccessCount()) {
            returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
            // 放行请求
            return;
        }
        chain.doFilter(request, response);
    }

    private void returnJson(HttpServletResponse response, String jsonString) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(jsonString);
        }
    }
}
